/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts } from 'qvog-dsl';
import {
  native,
  HomeCheckHint
} from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/hardcoded-password.md';
const DESCRIPTION = 'Potential hardcoded credential: Avoid embedding sensitive data such as passwords or API keys directly in source code.';

export default native<HomeCheckHint>()()
  .match((node): node is ts.PropertyDeclaration => {
    return ts.isPropertyDeclaration(node);
  })
  .when((node: ts.PropertyDeclaration) => {
    // private
    const hasPrivateModifier = node.modifiers?.some(mod => mod.kind === ts.SyntaxKind.PrivateKeyword);
    if (!hasPrivateModifier) { return false };

    const isStringType = node.type && node.type.kind === ts.SyntaxKind.StringKeyword;
    const isStringLiteralInitializer = node.initializer && ts.isStringLiteral(node.initializer) && node.initializer.text;
    
    if (!isStringType || !isStringLiteralInitializer) { return false };

    const varName = node.name.getText().toLowerCase();
    const sensitiveNames = ['password', 'passwd', 'pwd', 'secret', 'token', 'apikey'];
    return sensitiveNames.some(keyword => varName.includes(keyword));
  })
  .report({
    severity: SEVERITY,
    description: DESCRIPTION,
    docPath: DOC_PATH
  });
